﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MLSMooc.BO;
using MLSMooc.Helper;
using MLSMooc.DAO.Implement.Discussion;
using System.Threading.Tasks;
using MLSMooc.Service.Implement.Discussion;
using MLSMooc.Session.Model;
using MLSMooc.Session.Implement;
using MLSMooc.Session;
using System.IO;
using NPOI.SS.UserModel;
using System.Text;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.Util;

namespace MLSMooc.Controllers
{
    public class DiscussionController : Controller
    {
        DiscussionDAO discussionDAO = DiscussionDAO.Getinstance();
        DiscussionServiceImpl discussionService = DiscussionServiceImpl.Getinstance();

        [HttpGet]
        public async Task<string> GetByIdDiscussionList(int id)
        {
            var res = await discussionDAO.GetByIdDiscussionList(id);
            return SerializeHelper.SerializeJson(res);
        }

        [HttpGet]
        public async Task<string> GetByIdDiscussionReplyList(int id)
        {
            var res = await discussionDAO.GetByIdDiscussionReplyList(id);
            return SerializeHelper.SerializeJson(res);
        }

        [HttpGet]
        public async Task<string> GetDiscussionReplyList()
        {
            var res = await discussionDAO.GetDiscussionReplyList();
            return SerializeHelper.SerializeJson(res);
        }

        [HttpPost]
        public async Task<int> InsertDiscussion(DiscussionBO data)
        {
            SessionUser userSession = SessionUserService.GetInstance().DeSerializeDecrypt(SessionBaseOpt.GetSessionState<string>(ConstantHelper.USER, string.Empty));
            data.AdminId = userSession.Id;
            var res = await discussionService.InsertDiscussion(data);
            return res;
        }

        [HttpPost]
        public async Task<int> DeleteDiscussion(int id)
        {
            var res = await discussionService.DeleteDiscussion(id);
            return res;
        }

        [HttpPost]
        public async Task<int> DeleteDiscussionReply(int id)
        {
            var res = await discussionService.DeleteDiscussionReply(id);
            return res;
        }

        [HttpPost]
        public async Task<int> ReplyDiscussion(DiscussionReplyBO data)
        {
            SessionUser userSession = SessionUserService.GetInstance().DeSerializeDecrypt(SessionBaseOpt.GetSessionState<string>(ConstantHelper.USER, string.Empty));
            data.AdminId = userSession.Id;
            var res = await discussionService.ReplyDiscussion(data);
            return res;
        }

        [HttpPost]
        public async Task<int> UpCourseDisCount(int id)
        {
            var res =await discussionService.UpCourseDisCount(id);
            return res;
        }
        [HttpGet]
        public async Task<string> GetCourseIdDiscussionCountList(int courseid)
        {
            var res = await discussionDAO.GetByIdDiscussionList(courseid);
            return SerializeHelper.SerializeJson(res);
        }
        // GET: Excel
        /// <summary>
        /// mooc知识点讨论区导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> DownLd(int courseid ,string title)
        {

            try
            {
                string sheetNm = title;
                string filename = HttpUtility.UrlEncode(sheetNm, System.Text.Encoding.UTF8).ToString();
                IWorkbook workbook = await DownLdRSAList(courseid,title);
                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    Response.Clear();
                    Response.Buffer = true;
                    Response.Charset = Encoding.UTF8.BodyName;
                    Response.AppendHeader("Set-Cookie", "fileDownload=true; path=/");       //给jQuery.fileDownload.js做回调
                    Response.AppendHeader("Content-Disposition", $"attachment; filename={filename}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
                    Response.ContentEncoding = Encoding.UTF8;

                    Response.ContentType = "application/vnd.ms-excel; charset=UTF-8";


                    Response.BinaryWrite(ms.ToArray());

                    Response.End();

                    return new EmptyResult();

                }
            }
            catch (Exception ex)
            {

                throw;
            }


        }

        /// <summary>
        /// 知识点讨论区导出数据
        /// </summary>
        /// <returns></returns>
        public async Task<IWorkbook> DownLdRSAList(int courseid ,string title)
        {

            //查询用户名称数据
            var userNameList = await discussionDAO.GetUserNamerowseList();

            // List<BrowseBO> user = userNameList.ToList();

            //string[] userList = userNameList.ToArray();
            string shee1Nm = title;
            //查询表头数据
            //var shee1HeardList = await discussionDAO.GetExceHeardlMoocWebsiteBrowseList();
            //var ss = shee1HeardList.ToList();
            //ss.Insert(0, "姓名");
            //ss.Insert(1, "学号");
            //string[] heradList = ss.ToArray();

            string[] heradList = {"学号","学员姓名","发问次数","回答次数" };
            //查询数据
            List<DiscussionBO> xlist = new List<DiscussionBO>();
            var shee1Modellist = await discussionDAO.GetByCourseIdDiscussionList(courseid);
          
         
            foreach (var item in shee1Modellist)
            {
                DiscussionBO dd = new DiscussionBO();
                dd.AdminId = item.AdminId;
                dd.Cishu = item.Cishu;
                dd.Huifucishu = 0;
                xlist.Add(dd);
                var id = item.Id;
                
              
               
            }
            //int[] aa = did.ToArray();var result = string.Join(",", did);

            
            List<int> did = new List<int>();
            var dlistid = await discussionDAO.GetDiscussionReplyByCourseId(courseid);
            if (dlistid.Count()>0)
            {
                foreach (var item in dlistid)
                {
                    if (item!=null && item.Id!=0)
                    {
                        did.Add(item.Id);
                    }
                    
                }
                var dids = string.Join(",", did);
                var rshee1Modellist = await discussionDAO.GetByCourseIdRDiscussionList(dids);

                foreach (var item in rshee1Modellist)
                {
                    var cd = xlist.Where(c => c.AdminId == item.AdminId).ToList().FirstOrDefault();

                    if (cd != null)
                    {
                        cd.Huifucishu = item.Huifucishu;
                    }
                    else
                    {

                        DiscussionBO dd = new DiscussionBO();
                        dd.AdminId = item.AdminId;
                        dd.Cishu = 0;
                        dd.Huifucishu = item.Huifucishu;
                        xlist.Add(dd);
                    }

                }
            }
           
           

            //string[] sheet1Header = { "区域", "CAM", "省份", "城市", "FSS", "IPA Role", "IPA Grade", "GID", "CNDA", "公司名称", "公司地址", "用户名称", "英特尔® OpenVINO™工具套件初级课程(1小时15分钟23秒)", "英特尔® OpenVINO™工具套件中级课程(7小时50分钟7秒)", "基于英特尔技术的高职高教解决方案(0小时47分钟17秒)", "基于英特尔技术的普教解决方案(0小时6分钟21秒)", "边缘视觉智能研究与应用(0小时49分钟6秒)", "开源生态助力智能制造—基于英特尔® 架构的AI实践(0小时26分钟52秒)", "英特尔® 傲腾™ 持久内存加速企业AI规模化应用(0小时19分钟55秒)", "使用英特尔 oneAPI AI 分析工具包提升AI应用性能(1小时09分钟07秒)", "Analytics Zoo: 统一的大数据分析+AI平台(0小时21分钟51秒)", "使用BigDL和Analytics Zoo来开发统一的大数据分析和人工智能应用(0小时31分钟59秒)", "使用英特尔 BigDL搭建自动机器学习（AUTOML）应用(0小时38分钟20秒)", "英特尔® Deep Learning Boost加速深度学习推理(0小时19分钟04秒)" };


            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet;
            IRow row;
            int rowNumber;


            #region 表头样式
            //表头样式
            ICellStyle headerStyle = workbook.CreateCellStyle();//创建样式对象
            //字体
            IFont headerFont = workbook.CreateFont(); //创建一个字体样式对象
            headerFont.FontName = "Arial"; //和excel里面的字体对应
            headerFont.FontHeightInPoints = 8;//字体大小
            headerFont.IsBold = true;//字体加粗
            headerStyle.SetFont(headerFont); //将字体样式赋给样式对象

            //单元格
            headerStyle.Alignment = HorizontalAlignment.Center; // 表头水平居中
            headerStyle.VerticalAlignment = VerticalAlignment.Center;//表头垂直居中
            headerStyle.FillPattern = FillPattern.SolidForeground;
            headerStyle.FillForegroundColor = HSSFColor.Yellow.Index;//表头颜色换成正黄
            headerStyle.BorderBottom = BorderStyle.Thin;
            headerStyle.BorderLeft = BorderStyle.Thin;
            headerStyle.BorderRight = BorderStyle.Thin;
            headerStyle.BorderTop = BorderStyle.Thin;

            headerStyle.WrapText = true;
            #endregion

            #region 内容样式
            //表头样式
            ICellStyle contentStyle = workbook.CreateCellStyle();//创建样式对象
            //字体
            IFont contentFont = workbook.CreateFont(); //创建一个字体样式对象
            contentFont.FontName = "Arial"; //和excel里面的字体对应
            contentFont.FontHeightInPoints = 8;//字体大小
            contentStyle.SetFont(contentFont); //将字体样式赋给样式对象

            //单元格
            contentStyle.Alignment = HorizontalAlignment.Center; // 表头水平居中
            contentStyle.VerticalAlignment = VerticalAlignment.Center;//表头垂直居中

            contentStyle.BorderBottom = BorderStyle.Thin;
            contentStyle.BorderLeft = BorderStyle.Thin;
            contentStyle.BorderRight = BorderStyle.Thin;
            contentStyle.BorderTop = BorderStyle.Thin;

            contentStyle.WrapText = true;
            #endregion

            #region RSA店面
            //表头赋值，并且设置列宽
            sheet = workbook.CreateSheet(shee1Nm);
            rowNumber = 0;
            row = sheet.CreateRow(rowNumber);
            for (int i = 0; i < heradList.Count(); i++)
            {


                row.CreateCell(i).SetCellValue(heradList[i]);
                row.Cells[i].CellStyle = headerStyle;
                sheet.SetColumnWidth(i, 10 * (256 * 2));
                //if (i == 0)
                //{
                //    sheet.SetColumnWidth(i, 10 * (256 * 2));
                //    sheet.AddMergedRegion(new CellRangeAddress(1, 1, stratindex, endindex));
                //}
                //else
                //{
                //    sheet.SetColumnWidth(i, 10 * 256*2);
                //}
            }
            ++rowNumber; //表头赋值 第一行




            //内容赋值
            List<BrowseBO> userlist = userNameList.ToList();
            IEnumerable<DiscussionBO> shee1list = xlist;
            if (!shee1list.Any())
            {
                row = sheet.CreateRow(rowNumber);
                row.CreateCell(0).SetCellValue("暂无讨论数据");
                ++rowNumber;
            }
            else
            {
                try
                {


                    foreach (var users in userlist)
                    {

                        var CNameList = shee1list.Where(s => s.AdminId == users.Id).ToList();
                        if (CNameList.Count() <= 0)
                        {

                            row = sheet.CreateRow(rowNumber);

                            row.CreateCell(0).SetCellValue(users.AdminName);
                            row.CreateCell(1).SetCellValue(users.AName);

                            for (int i = 2; i < heradList.Length; i++)
                            {
                                row.CreateCell(i).SetCellValue("0");
                            }
                            for (int k = 0; k < heradList.Length; k++)
                            {

                                row.Cells[k].CellStyle = contentStyle;
                            }
                            ++rowNumber;
                        }
                        else
                        {
                            row = sheet.CreateRow(rowNumber);

                            row.CreateCell(0).SetCellValue(users.AdminName);
                            row.CreateCell(1).SetCellValue(users.AName);

                            for (int i = 2; i < heradList.Length; i++)
                            {
                                row.CreateCell(i).SetCellValue("0");
                            }

                            foreach (var item in CNameList)
                            {

                                if (item.AdminId == users.Id)
                                {
                                    row.CreateCell(2).SetCellValue(item.Cishu);
                                    row.CreateCell(3).SetCellValue(item.Huifucishu);
                                }
                                //for (int i = 2; i < heradList.Length; i++)
                                //{

                                //    //if (item.AdminId == users.Id && item.CName == heradList[i])
                                //    //{
                                //    //    row.CreateCell(i).SetCellValue(item.BrTime);
                                //    //}
                                //    if (item.AdminId == users.Id)
                                //    {
                                //        row.CreateCell(2).SetCellValue(item.Cishu);
                                //    }

                                //}
                            }
                      

                            for (int k = 0; k < heradList.Length; k++)
                            {

                                row.Cells[k].CellStyle = contentStyle;
                            }
                            ++rowNumber;
                        }

                    }


                }
                catch (Exception ex)
                {

                    throw;
                }






            }
            #endregion

            return workbook;
        }

    }
}